// db/index.js
const mysql = require("mysql2/promise");
const { database } = require("../config");
console.log("process.env", database.DB_HOST);
// 数据库配置（从.env读取）
const config = {
  host: database.host,
  port: database.port,
  user: database.user,
  password: database.password,
  database: database.name,
  waitForConnections: true, // 连接超额是否等待
  connectionLimit: 10, // 连接池最大连接数
  queueLimit: 0,
};

// 创建连接池
const pool = mysql.createPool(config);

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();

    console.log("✅ 数据库连接成功");
    connection.release(); // 释放连接
  } catch (err) {
    console.error("❌ 数据库连接失败:", err.message);
  }
}

// 执行SQL语句的工具函数（封装增删改查）
async function executeSql(sql, params = []) {
  try {
    const [results] = await pool.execute(sql, params);
    return { success: true, data: results };
  } catch (err) {
    console.error("SQL执行错误:", err.message);
    return { success: false, error: err.message };
  }
}

// async function test(table, id, key) {
//   const sql = `select * from ${table} where ${id}= ?`;
//   const { success, data } = await executeSql(sql, [12222]);
//   console.log("result", success, data);
// }
// test("user", "id", 12222);
module.exports = {
  pool,
  testConnection,
  executeSql,
};
